# -*- coding: utf-8 -*-

from core.viewset import CustomModelViewSet
from rest_framework.decorators import action
from .utils.gen_outline import generate_outline
from apps.sys.models import DictData
from bs4 import BeautifulSoup
from .models import TestPlan
from .serializers import *
from .resources import *
from .filters import *


class TestPlanViewSet(CustomModelViewSet):
    """
    测试计划-视图
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """

    queryset = TestPlan.objects.all()
    serializer_class = TestPlanSerializer
    list_serializer_class = ListTestPlanSerializer
    filterset_class = TestPlanFilterSet
    import_resources = TestPlanImportResouces
    export_resources = TestPlanExportResouces

    @action(detail=True, methods=["POST"])
    def outline(self, request, pk=None, *args, **kwargs):
        # 预加载相关的testcase并获取目标testplan
        testplan = TestPlan.objects.prefetch_related("requirements__testcase_set").get(
            id=pk
        )
        # 获取所有需求并创建需求分类到名称的映射字典
        requirements = testplan.requirements.all()

        dataset = {
            "product_name": testplan.product.name,
            "product_number": testplan.product.number,
            "product_version": testplan.version.name,
            "product_description": testplan.product.remark,
            "product_requirements_testcases": [],
        }
        classify_dict = {}

        # 预加载和缓存测试计划的测试用例IDs
        testplan_testcase_ids = set(testplan.testcases.values_list("id", flat=True))

        for requirement in requirements:
            classify_name = requirement.classify_label
            # 检查是否已经添加了这个分类
            if classify_name not in classify_dict:
                classify_node = {"name": classify_name, "children": []}
                classify_dict[classify_name] = classify_node
                dataset["product_requirements_testcases"].append(classify_node)
            else:
                classify_node = classify_dict[classify_name]

            testcases_data = [
                {
                    "name": tc.name,
                    "steps": tc.steps,
                    "module": tc.module.name,
                    "description": tc.description,
                    "precondition": tc.precondition,
                }
                for tc in requirement.testcase_set.all()
                if tc.id in testplan_testcase_ids
            ]

            classify_node["children"].append(
                {
                    "name": requirement.name,
                    "children": testcases_data,
                }
            )
        return generate_outline(dataset=dataset, params=request.data)
